//
//  MyReportViewController.m
//  work
//
//  Created by 徐宏飞 on 16/6/2.
//  Copyright © 2016年 方伟. All rights reserved.
//

#import "MyReportViewController.h"
#import "WorkerCompleteCollectionViewCell.h"
#import "TZImagePickerController.h"     //选取相册
#import "XHF_LbumViewController.h"      //相册
#import "GoingProjectModel.h"



static NSString *collectionViewCell_ID = @"WorkerCompleteCollectionViewCell";


@interface MyReportViewController ()<
UICollectionViewDelegate,
UICollectionViewDataSource,
UITextViewDelegate,
TZImagePickerControllerDelegate,
imageUploadToolDelegate,
NetworkToolerDelegate
>


@property (weak, nonatomic) IBOutlet UILabel *lblTime;
@property (weak, nonatomic) IBOutlet UILabel *lblAddress;
@property (weak, nonatomic) IBOutlet UILabel *lblowner;
@property (weak, nonatomic) IBOutlet UILabel *lblTel;
@property (weak, nonatomic) IBOutlet UILabel *lblPrice;

@property (weak, nonatomic) IBOutlet UITextView *upTextView;


@property (weak, nonatomic) IBOutlet UICollectionView *upJobCollectionView;
@property (nonatomic ,strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) NSMutableArray *allImagesArray;
@property (weak, nonatomic) IBOutlet UIButton *btnUpData;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollV;
@property (weak, nonatomic) IBOutlet UIView *baseView;
@property (nonatomic, strong) UITapGestureRecognizer *tap;




@property (nonatomic, assign) BOOL isShow;
@property (nonatomic, strong) NSMutableArray *selectedPhotos;
@property (nonatomic, strong)TZImagePickerController *imagePickerVc;
@property (nonatomic, strong) TZImageManager   *TZImanagers;
@property (nonatomic ,strong)imageUploadTool *imageuploadtool;
@property (nonatomic, strong) ZhuangxiuManager *manager;
@property (nonatomic, strong) NetworkTooler *network;


@property (nonatomic, strong) NSMutableArray *imageUpArray;






@end

@implementation MyReportViewController




#pragma mark - life cycle
- (void)initNavigationBar
{
    self.enableReturnButton = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _upTextView.delegate = self;
    self.title = _pickDay;
    _selectedPhotos = [NSMutableArray new];
    _imageUpArray  = [NSMutableArray new];
    self.manager = [ZhuangxiuManager shareManager];
    _network  = [NetworkTooler new];

//    [_baseView addGestureRecognizer:self.tap];
    [self configurationUpJobCollectionView];
    [self configurationData];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"WorkReport-me"];//("PageOne"为页面名称，可自定义)
    
    _scrollV.scrollEnabled = NO;
 
    
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //监听键盘的弹出事件
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    [center addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"WorkReport-me"];
    
    //移除监听
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}




#pragma mark - Data
- (void) _upMyReportWorkRequst{

    NSString *imageURLstring = [_imageUpArray componentsJoinedByString:@","];

    
    _network.delegate = self;
    
    NSDictionary *parameters = @{
                                 @"day":self.title,
                                 @"session_id":self.manager.sessionid,
                                 @"piclist":imageURLstring,
                                 @"content":_upTextView.text,
                                 @"order_id":self.model.order_id
                                 };
    
    NSLog(@"上传参数:%@", parameters);
    
    [_network parameters:parameters withURL: addTaskByDay_show  withIsPaparameters:YES];
    
    
    

}





#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
    
    NSLog(@"%@", textView.text);
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
      
        [self.view endEditing:YES];
        //在这里做你响应return键的代码
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    
    return YES;
}
#pragma mark - imageUploadToolDelegate

- (void)returnImageURL:(NSString *)imageURL{
    
    NSLog(@"%@",imageURL)
    
    [_imageUpArray addObject:imageURL];
   
    if (_imageUpArray.count == _selectedPhotos.count) {
        
        [self _upMyReportWorkRequst];
    }
    
    
    
}
- (void)returnError:(NSString *)error{
    [GiabHUD hideUIBlockingIndicator];

    
    
    [self showAlertWithTitle:@"温馨提示" message:error cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
}

#pragma mark - NetworkToolerDelegate

- (void)returnData:(id)data{
    [GiabHUD hideUIBlockingIndicator];

   [self.navigationController popViewControllerAnimated:YES];
        
    
    
    
}
- (void)returnRequestError:(NSError *)error{
    
    [GiabHUD hideUIBlockingIndicator];

}
- (void)returnMsg:(NSString *)Msg{
    [GiabHUD hideUIBlockingIndicator];

    //失败
    //    NSString *msg = [json objectForKey:@"msg"];

    [self showAlertWithTitle:@"温馨提示" message:Msg cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
}

#pragma mark - TZImagePickerControllerDelegate


/// 用户选择好了图片，如果assets非空，则用户选择了原图。
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    
    //    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    
    //区分是否显示了原图
    if (isSelectOriginalPhoto) {
        
        if (!_TZImanagers) {
            _TZImanagers = [TZImageManager new];
        }
        
        [_selectedPhotos removeAllObjects];
        
        for (int i = 0; i<assets.count; i++) {
            //获取原图
            [ _TZImanagers getOriginalPhotoWithAsset:assets[i] completion:^(UIImage *photo, NSDictionary *info) {
                if (photo.size.width  >1200) {
                    photo = [photo scaleToSize:photo size:CGSizeMake(1200, 80)];
                }
                [_selectedPhotos addObject:photo];
            }];
        }
    }else{
        
        [_selectedPhotos removeAllObjects];
        _selectedPhotos = [NSMutableArray  arrayWithArray:photos];
    }

    [self.upJobCollectionView reloadData];
}


#pragma mark - event response
- (void)TapAction{
    [self.view endEditing:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


- (IBAction)btnUpDataAction:(id)sender {
    //上传内容
    NSLog(@"%@", _upTextView.text);
    if ([_upTextView.text isEqualToString:@""]) {
        [self showAlertWithTitle:@"温馨提示" message:@"您还没有填写内容哦!" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    
    if (_selectedPhotos.count == 0) {
        [self showAlertWithTitle:@"温馨提示" message:@"请完善图片信息!" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    [self upimageToUpyun];
    
}



-(void)selectPhotosAction{
    
    
    
    if (_imagePickerVc) {
        
        _imagePickerVc = nil;
    }
    
    _imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:5 delegate:self];
    //        _imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    // 在这里设置imagePickerVc的外观
    _imagePickerVc.navigationBar.barTintColor = COLOR_THEHE;
    _imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    _imagePickerVc.oKButtonTitleColorNormal = COLOR_THEHE;
    
    
    //    _imagePickerVc.selectedAssets = _selectedAssets; // optional, 可选的
    
    // Set allow picking video & photo & originalPhoto or not
    // 设置是否可以选择视频/图片/原图
    // imagePickerVc.allowPickingVideo = NO;
    // imagePickerVc.allowPickingImage = NO;
    // imagePickerVc.allowPickingOriginalPhoto = NO;
    
    [self presentViewController:_imagePickerVc animated:YES completion:nil];
    
    
}


- (void)keyboardWillChangeFrame:(NSNotification *)notification{
    //获取键盘的Y值
    CGRect rect = [[notification.userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    CGFloat keybordY = rect.origin.y;
    CGFloat tranformValue = keybordY - self.view.frame.size.height;
    
    CGFloat value = 0.0;
    if (SCREEN_HEIGHT == 667) {  //6s
        value = 0;
    }
    if (SCREEN_HEIGHT == 568) {  //5 5s
        value = 0.6;
    }
    
    if (SCREEN_HEIGHT == 480) {  // 4s
        value = 0.8;
    }
    
    if (tranformValue >= 0) {
        tranformValue = 0;
    }
    
    CGPoint point = CGPointMake(0, -tranformValue*value);
    _scrollV.contentOffset = point;
    
}






#pragma mark - private methods
- (void)configurationUpJobCollectionView{
    
    //item 比例4:5
    CGSize size = CGSizeMake(118, 100);
    //4  4s  5  5s
    if (SCREEN_WIDTH == 320) {
        size = CGSizeMake(86, 70);
    }
    
    //6 6s
    if (SCREEN_WIDTH == 375) {
        size = CGSizeMake(105, 90);
    }
    
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.itemSize = size;
    self.flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 20, 10);
    self.flowLayout.minimumLineSpacing = 12;
    self.flowLayout.minimumInteritemSpacing = 8;
    
    _upJobCollectionView.backgroundColor = UIColorFromRGB(0xEBEBEB);
    _upJobCollectionView.collectionViewLayout = self.flowLayout;
    _upJobCollectionView.delegate = self;
    _upJobCollectionView.dataSource =self;
    [_upJobCollectionView registerNib:[UINib nibWithNibName:@"WorkerCompleteCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:collectionViewCell_ID];
    
}


- (void)configurationData{
    
    NSString *start = [NSString getBeijingDayWithStrTime:self.model.start_day];
    NSString *end = [NSString getBeijingDayWithStrTime:self.model.end_day];
    self.lblTime.text = [NSString stringWithFormat:@"时间: %@至%@", start, end];
    self.lblAddress.text = [NSString stringWithFormat:@"工作地点: %@", self.model.address];
    self.lblowner.text = [NSString stringWithFormat:@"业主: %@", self.model.contact_name];
    self.lblTel.text = [NSString stringWithFormat:@"联系电话: %@", self.model.mobile];
    self.lblPrice.text = [NSString stringWithFormat:@"价格: %@元/平方", self.model.price];
    
}





- (void)deleteBtnClik:(UIButton *)sender {
    
    
    [_selectedPhotos removeObjectAtIndex:sender.tag-2];
    
    //    _layout.itemCount = _selectedPhotos.count;
    
    [self.upJobCollectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [self.upJobCollectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [self.upJobCollectionView reloadData];
        
    }];
    


}

- (void)WorkerCompleteReturnArray:(NSMutableArray *)array andIndex:(NSInteger)index{
    //弹出相册
    if (array.count == 0 || array.count < index) {
        return;
    } else {
        //进入相册
        XHF_LbumViewController *lbumVC = [[XHF_LbumViewController alloc] init];
        lbumVC.imgArr = array;
        //        NSLog(@"%@", array);
        lbumVC.currentIndex = index;
        lbumVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentViewController:lbumVC animated:YES completion:nil];
    }
}

//上传到UPYUN
-(void)upimageToUpyun{
    
    [GiabHUD showUIBlockingIndicatorWithText:@"正在上传..."];

    
    if (!_imageuploadtool) {
        _imageuploadtool = [imageUploadTool new];
        
    }
    
    
    _imageuploadtool.worker_id  = self.manager.worker_id ;
    //上传图片
    _imageuploadtool.type = UPLOADIMAGETYPETODAY;
    _imageuploadtool.delegate = self;
    
    for (int i = 0; i<_selectedPhotos.count; i++) {
        
        _imageuploadtool.selectedImage = _selectedPhotos[i];
        _imageuploadtool.index = i;
        [_imageuploadtool uplodImage];
    }
    
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.selectedPhotos.count + 2;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    WorkerCompleteCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionViewCell_ID forIndexPath:indexPath];
    
    
    if (indexPath.row == 0) {
        
        cell.imgComplete.image = FW_IMAGE(@"take-photo");
        cell.deleteBtn.hidden = YES;
        
        
    }else if(indexPath.row == 1){
        
        cell.imgComplete.image = FW_IMAGE(@"delete");
        cell.deleteBtn.hidden = YES;
        
        
    } else {
         cell.imgComplete.image = self.selectedPhotos[indexPath.row - 2];
        
    
        if (_isShow) {
            cell.deleteBtn.hidden = NO;
            
        }else{
            cell.deleteBtn.hidden = YES;
        }
        
    }
    
    cell.deleteBtn.tag = indexPath.row;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        
        [self selectPhotosAction];
        
        
    }else if(indexPath.row == 1){
        
        _isShow = !_isShow;
        [self.upJobCollectionView reloadData];
        
        
    }
    else{
        if(!_isShow){
            [self WorkerCompleteReturnArray:self.selectedPhotos andIndex:indexPath.row - 2];
        }
        
        return;
    }
}




- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    //    if (sourceIndexPath.item == 0 || destinationIndexPath.item == 0) return;
    //    UIImage *image = _selectedPhotos[sourceIndexPath.item];
    //    if (image) {
    //        [_selectedPhotos exchangeObjectAtIndex:sourceIndexPath.item withObjectAtIndex:destinationIndexPath.item];
    //        [_selectedAssets exchangeObjectAtIndex:sourceIndexPath.item withObjectAtIndex:destinationIndexPath.item];
    //        [self.collectionViewImages reloadData];
    //    }
}











#pragma mark - setter and getter
//- (UITapGestureRecognizer *)tap{
//    if (!_tap) {
//        _tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TapAction)];
//    }
//    return _tap;
//}
//- (void)setSelectedPhotos:(NSMutableArray *)selectedPhotos{
//    _selectedPhotos = selectedPhotos;
//    [self.collectionViewImages reloadData];
//}





- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
//    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
